<template>
  <div class="carousel-container">
    <el-card class="header-card">
      <div class="header-actions">
        <div class="title">
          <el-icon><Picture /></el-icon>
          <span>轮播图管理</span>
        </div>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增轮播图
        </el-button>
      </div>
    </el-card>

    <el-card class="content-card">
      <el-table
        v-loading="uploadLoading"
        :data="bannerForm"
        border
        style="width: 100%"
        height="60vh"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="name" label="名称" min-width="120" />
        <el-table-column label="图片" width="120" align="center">
          <template #default="{ row }">
            <div class="banner-image-wrapper" @click="handlePreview(row)">
              <el-image
                :src="formatImageUrl(row.url)"
                fit="cover"
                class="banner-image"
                :preview-teleported="false"
                preview-disabled
              >
                <template #placeholder>
                  <div class="image-placeholder">
                    <el-icon><Loading /></el-icon>
                  </div>
                </template>
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="descs"
          label="描述"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column label="推荐" width="80" align="center">
          <template #default="{ row }">
            <el-tag
              :type="row.isRecommend === 1 ? 'success' : 'info'"
              class="status-tag"
              @click="handleEdit(row)"
            >
              {{ row.isRecommend === 1 ? "是" : "否" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="轮播" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isBanner === 1 ? 'warning' : 'info'">
              {{ row.isBanner === 1 ? "是" : "否" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="pid" label="排序" width="80" align="center" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag
              :type="row.status === 1 ? 'success' : 'danger'"
              class="status-tag"
              @click="handleStatusChange(row)"
            >
              {{ row.status === 1 ? "展示中" : "已隐藏" }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="updatedTime"
          label="更新时间"
          width="160"
          align="center"
        />
        <el-table-column
          prop="updatedBy"
          label="操作人"
          width="100"
          align="center"
        /> -->
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button-group>
              <el-button link type="primary" @click="handleEdit(row)">
                <el-icon><EditPen /></el-icon>
                编辑
              </el-button>
              <el-button link type="danger" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                隐藏轮播图
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑/添加对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      :width="dialogWidth"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="bannerForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="bannerForm.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="图片" prop="url">
          <el-upload
            class="banner-uploader"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            action="/api/upload"
          >
            <el-image
              v-if="bannerForm.url"
              :src="bannerForm.url"
              class="uploaded-image"
              fit="cover"
            />
            <div v-else class="upload-placeholder">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <span>点击上传图片</span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述" prop="descs">
          <el-input
            v-model="bannerForm.descs"
            type="textarea"
            rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>
        <el-form-item label="推荐">
          <el-switch
            v-model="bannerForm.isRecommend"
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
        <el-form-item label="轮播">
          <el-switch
            v-model="bannerForm.isBanner"
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="bannerForm.sort"
            :min="1"
            :max="99"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="bannerForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="显示"
            inactive-text="隐藏"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="submitLoading"
            @click="handleSubmit"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览组件 -->
    <el-image-viewer
      v-if="previewVisible"
      :url-list="tableData.map(item => item.url)"
      :initial-index="previewIndex"
      :hide-on-click-modal="true"
      :close-on-click-modal="true"
      @close="previewVisible = false"
    />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import Delete from "@iconify-icons/ep/delete";
import Plus from "@iconify-icons/ep/plus";
import EditPen from "@iconify-icons/ep/edit";
import WarnTriangleFilled from "@iconify-icons/ep/warn-triangle-filled";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps } from "element-plus";
import { getBannerRecommend, updateBannerStatus } from "@/api/banner";
import { formatImageUrl } from "@/utils/tools";

defineOptions({
  name: "CarouselImage"
});

onMounted(() => {
  getBannerRecommendAll();
});

// 定义数据类型
interface BannerItem {
  pid: string;
  name: string;
  isRecommend: number;
  isBanner: number;
  url: string;
  descs: string;
  content: string | null;
}

// 表格数据
const bannerForm = ref<BannerItem[]>([]);
const uploadLoading = ref(false);

// 对话框控制
const dialogVisible = ref(false);
const dialogType = ref("add"); // edit, add
const dialogTitle = ref("");
const dialogWidth = ref("500px");

// 图片上传相关
const imageUrl = ref("");

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 加载状态
const submitLoading = ref(false);

// 图片预览相关
const previewVisible = ref(false);
const previewIndex = ref(0);

// 表单校验规则
const formRules = {
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  url: [{ required: true, message: "请上传图片", trigger: "change" }],
  descs: [{ required: true, message: "请输入描述", trigger: "blur" }]
};

// 获取轮播图列表
const getBannerRecommendAll = async () => {
  uploadLoading.value = true;
  try {
    const res = await getBannerRecommend();
    if (res.code === 200) {
      bannerForm.value = res.data;
      // bannerForm.value.map(item => {
      //   item.url = formatImageUrl(item.url);
      // });
    } else {
      ElMessage.error(res.message || "获取数据失败");
    }
  } catch (error) {
    ElMessage.error("获取数据失败");
  } finally {
    uploadLoading.value = false;
  }
};

// 隐藏轮播图
const handleDelete = async (row: BannerItem) => {
  ElMessageBox.confirm("确定要隐藏该轮播图吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      const res = await updateBannerStatus({
        pid: row.pid,
        isBanner: 0
      });

      if (res.code === 200) {
        ElMessage.success("隐藏成功");
        getBannerRecommendAll();
      } else {
        ElMessage.error(res.message || "操作失败");
      }
    } catch (error) {
      ElMessage.error("操作失败");
    }
  });
};

// 编辑轮播图
const handleEdit = async (row: BannerItem) => {
  try {
    const res = await updateBannerStatus({
      pid: row.pid,
      isRecommend: row.isRecommend === 1 ? 0 : 1
    });

    if (res.code === 200) {
      ElMessage.success("更新成功");
      getBannerRecommendAll();
    } else {
      ElMessage.error(res.message || "操作失败");
    }
  } catch (error) {
    ElMessage.error("操作失败");
  }
};

// 修改状态
const handleStatusChange = row => {
  const statusText = row.status === 1 ? "隐藏" : "展示";
  ElMessageBox.confirm(`确定要${statusText}该轮播图吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      row.status = row.status === 1 ? 0 : 1;
      // TODO: 调用状态修改接口
      ElMessage.success(`${statusText}成功`);
    })
    .catch(() => {
      // 取消操作，不需要做任何处理
    });
};

// 上传图片成功回调
const handleUploadSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  uploadLoading.value = false;
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  bannerForm.value.url = imageUrl.value;
};

// 上传前校验
const beforeUpload: UploadProps["beforeUpload"] = file => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("上传图片只能是 JPG/PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过 2MB!");
    return false;
  }
  uploadLoading.value = true;
  return true;
};

// 重置表单
const resetForm = () => {
  bannerForm.value.pid = "";
  bannerForm.value.name = "";
  bannerForm.value.isRecommend = 0;
  bannerForm.value.isBanner = 0;
  bannerForm.value.url = "";
  bannerForm.value.descs = "";
  bannerForm.value.content = null;
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  // TODO: 实现分页查询
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  // TODO: 实现分页查询
};

// 修改提交方法
const handleSubmit = async () => {
  submitLoading.value = true;
  try {
    const formData = {
      ...bannerForm,
      pid: bannerForm.value.pid || undefined // 新增时不需要pid
    };
    // TODO: 调用API保存数据
    ElMessage.success(bannerForm.value.pid ? "更新成功" : "添加成功");
    dialogVisible.value = false;
    await loadData(); // 重新加载数据
  } finally {
    submitLoading.value = false;
  }
};

// 加载数据方法
const loadData = async () => {
  try {
    const res = await getBannerRecommend();
    if (res.code === 200) {
      bannerForm.value = res.data;
    }
  } catch (error) {
    ElMessage.error("获取数据失败");
  }
};

// 处理图片预览
const handlePreview = (row: BannerItem) => {
  const imageUrl = formatImageUrl(row.url);
  const h = 600;
  const w = 800;
  const top = (window.screen.height - h) / 2;
  const left = (window.screen.width - w) / 2;
  window.open(
    imageUrl,
    "图片预览",
    `height=${h}, width=${w}, top=${top}, left=${left}, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no`
  );
};
</script>

<style lang="scss" scoped>
.carousel-container {
  padding: 20px;
  background: #f5f7fa;

  .header-card {
    margin-bottom: 20px;

    .header-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: 600;
        color: #303133;

        .el-icon {
          font-size: 20px;
          color: #409eff;
        }
      }
    }
  }

  .content-card {
    .banner-image-wrapper {
      cursor: zoom-in;
      transition: transform 0.3s;

      &:hover {
        transform: scale(1.05);
      }
    }

    .banner-image {
      width: 80px;
      height: 80px;
      border-radius: 4px;
      background-color: #f5f7fa;
    }

    .image-placeholder,
    .image-error {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      background: #f5f7fa;
      color: #909399;
      font-size: 20px;
    }

    .image-placeholder {
      .el-icon {
        animation: rotating 2s linear infinite;
      }
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }

    .status-tag {
      cursor: pointer;
      padding: 0 15px;
      height: 28px;
      line-height: 26px;
      font-size: 13px;

      &:hover {
        opacity: 0.85;
      }
    }
  }

  .banner-uploader {
    .uploaded-image {
      width: 360px;
      height: 180px;
      border-radius: 4px;
    }

    .upload-placeholder {
      width: 360px;
      height: 180px;
      border: 1px dashed var(--el-border-color);
      border-radius: 4px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
        color: var(--el-color-primary);
      }

      .upload-icon {
        font-size: 28px;
        margin-bottom: 8px;
        color: #909399;
      }
    }

    .upload-tip {
      margin-top: 8px;
      font-size: 12px;
      color: #909399;
    }
  }
}

// 优化预览样式
:deep(.el-image-viewer__wrapper) {
  .el-image-viewer__mask {
    opacity: 0.9;
    backdrop-filter: blur(5px);
    background-color: #0000005c;
    cursor: pointer;
  }

  .el-image-viewer__img {
    transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }

  .el-image-viewer__prev,
  .el-image-viewer__next {
    transition: all 0.3s;
    background-color: rgba(0, 0, 0, 0.3);

    &:hover {
      background-color: rgba(0, 0, 0, 0.5);
    }
  }

  .el-image-viewer__close {
    transition: all 0.3s;
    background-color: rgba(0, 0, 0, 0.3);
    border-radius: 50%;
    padding: 8px;

    &:hover {
      background-color: rgba(0, 0, 0, 0.5);
      transform: rotate(90deg);
    }
  }

  .el-image-viewer__actions {
    opacity: 0.9;
    padding: 12px 20px;
    background: rgba(0, 0, 0, 0.3);
    border-radius: 20px;
    backdrop-filter: blur(5px);

    .el-image-viewer__actions__inner {
      button {
        transition: all 0.3s;

        &:hover {
          transform: scale(1.1);
        }
      }
    }
  }
}

@keyframes rotating {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
